#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h> // 引入头文件

// protobuf生成的头文件，包含两个信息和应用的头文件
#include "msg.grpc.pb.h"
#include "msg.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;

// service MsgService { // 定义服务, 流数据放到括号里面
//   rpc GetMsg (MsgRequest) returns (MsgResponse){}
// }
 
// message MsgRequest { // 请求的结构
//   int32 num1 = 1;
//   int32 num2 = 2;
// }
 
// message MsgResponse { // 回应的结果
//   int32 sum = 1;
// }

// 这个类随意起名, 只要继承 MsgService::Service就行了
// 具体见msg.grpc.pb.cc中MsgService::Service::Service() 
class MyMsgService final : public MsgService::Service {
  Status GetMsg(ServerContext* context, const MsgRequest* request,
                  MsgResponse* reply) override {

    std::string str1("Hello ");
    reply->set_sum(request->num1() + request->num2()); // 给reply.sum赋值
    
    return Status::OK;
  }
};

void RunServer() {
  std::string server_address("0.0.0.0:50051");
  MyMsgService service;

  ServerBuilder builder;
  // Listen on the given address without any authentication mechanism.
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  // Register "service" as the instance through which we'll communicate with
  // clients. In this case it corresponds to an *synchronous* service.
  builder.RegisterService(&service);
  // Finally assemble the server.
  std::unique_ptr<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;

  // Wait for the server to shutdown. Note that some other thread must be
  // responsible for shutting down the server for this call to ever return.
  server->Wait();
}

int main(int argc, char** argv) {
  RunServer();

  return 0;
}


